package rpc;

import com.rabbitmq.client.*;
import config.RabbitConfig;

import java.io.IOException;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

/**
 * @author tuyou_cd
 * @date 2020/12/18 14:46
 */
public class RPCClient {

    private Connection connection;
    private Channel channel;

    /**
     * 回复队列
     */
    private String replyQueueName;

    public RPCClient() throws IOException, TimeoutException {
        channel = RabbitConfig.createChannel();

        //监听回复队列
        replyQueueName = channel.queueDeclare().getQueue();
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String response = new String(body);
                System.out.println(properties.getCorrelationId() + " [.] Got '" + response + "'");
                System.exit(1);
            }
        };
        channel.basicConsume(replyQueueName, true, consumer);
    }

    /**
     * 发送消息
     *
     * @param number
     * @throws IOException
     * @throws ShutdownSignalException
     * @throws ConsumerCancelledException
     */
    public void call(int number) throws IOException,
            ShutdownSignalException, ConsumerCancelledException {
        String corrId = UUID.randomUUID().toString();

        AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
                .correlationId(corrId)
                .replyTo(replyQueueName)
                .build();

        System.out.println(" [x] Requesting n*n(" + number + ")");
        channel.basicPublish("", RPCServer.RPC_QUEUE_NAME, props, String.valueOf(number).getBytes());
    }

    public void close() throws Exception {
        connection.close();
    }

    public static void main(String args[]) throws Exception {
        RPCClient fibRpc = new RPCClient();
        fibRpc.call(new Random().nextInt(10));
    }
}
